import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';

class ChatMessageMenu extends StatelessWidget {
  const ChatMessageMenu({
    Key? key,
    required this.message,
    required this.isISend,
    required this.child,
    this.controller,
    this.onCopyMessage,
    this.onQuoteMessage,
    this.onDeleteMessage,
    this.onRevokeMessage,
    this.onForwardMessage,
    this.onMultiSelectMessage,
    this.onPinMessage,
    this.isMessagePinned = false, // 新增参数
    this.isSingleChat = false, // 新增参数：是否为一对一私聊
    this.isMultiSelectMode = false, // 新增参数：是否为多选模式
    this.canPinMessage = false, // 新增参数：是否有置顶权限
  }) : super(key: key);

  final Message message;
  final bool isISend;
  final Widget child;
  final CustomPopupMenuController? controller;
  final Function(Message message)? onCopyMessage;
  final Function(Message message)? onQuoteMessage;
  final Function(Message message)? onDeleteMessage;
  final Function(Message message)? onRevokeMessage;
  final Function(Message message)? onForwardMessage;
  final Function(Message message)? onMultiSelectMessage;
  final Function(Message message)? onPinMessage;
  final bool isSingleChat; // 新增参数：是否为一对一私聊
  final bool isMessagePinned; // 新增参数
  final bool isMultiSelectMode; // 新增参数：是否为多选模式
  final bool canPinMessage; // 新增参数：是否有置顶权限

  @override
  Widget build(BuildContext context) {
    // 在多选模式下，禁用长按菜单
    if (isMultiSelectMode) {
      return child;
    }
    
    return CopyCustomPopupMenu(
      pressType: PressType.longPress,
      controller: controller,
      showArrow: true,
      arrowColor: Styles.c_0C1C33,
      barrierColor: Colors.black26,
      verticalMargin: 1.h,
      horizontalMargin: 70.w,
      menuBuilder: () => _buildMenuContent(),
      child: child,
    );
  }

  Widget _buildMenuContent() {
    final menuItems = _getMenuItems();
    
    // 将菜单项分为两行，每行最多4个
    final firstRowItems = menuItems.take(4).toList();
    final secondRowItems = menuItems.length > 4 ? menuItems.skip(4).take(3).toList() : <MenuItemData>[];
    
    return Container(
      decoration: BoxDecoration(
        color: Color(0xFF4A4A4A), // 深灰色背景，与设计图一致
        borderRadius: BorderRadius.circular(12.r), // 调整圆角
      ),
      padding: EdgeInsets.symmetric(vertical: 1.h, horizontal: 1.w), // 添加整
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center, // 确保Column内容居中
        children: [
          
          // 第一行菜单项
          _buildMenuRow(firstRowItems),
          if (secondRowItems.isNotEmpty) ...[
            Container(
            height: 1.h,
            margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
            color: Colors.white.withOpacity(0.2),
            ),
            // 第二行菜单项
            _buildMenuRow(secondRowItems),
          ],
        ],
      ),
    );
  }

  Widget _buildMenuRow(List<MenuItemData> items) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 6.w),
      child: Row(
        // mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start, // 添加这行，让菜单项靠左排列
        crossAxisAlignment: CrossAxisAlignment.center, // 确保菜单项垂直居中
        children: items.map((item) => _buildMenuItem(item)).toList(),
      ),
    );
  }

  Widget _buildMenuItem(MenuItemData item) {
    return GestureDetector(
      onTap: () {
        controller?.hideMenu();
        item.onTap?.call();
      },
      child: Container(
        width: 42.w,
        margin: EdgeInsets.symmetric(horizontal: 6.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 25.w,
              height: 25.w,
              decoration: BoxDecoration(
                color: Color(0xFF4A4A4A),
                borderRadius: BorderRadius.circular(6.r),
              ),
              child: Center(
                child: item.icon,
              ),
            ),
            // SizedBox(height: 0.2.h),
            Text(
              item.title,
              style: TextStyle(
                color: Colors.white,
                fontSize: 9.sp,
                fontWeight: FontWeight.w400,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }

  List<MenuItemData> _getMenuItems() {
    List<MenuItemData> items = [];

    // 复制 - 仅文本消息支持
    if (message.isTextType) {
      items.add(MenuItemData(
        icon: Icon(
          Icons.copy,
          color: Colors.white,
          size: 20.w,
        ),
        title: StrRes.menuCopy,
        onTap: _copyMessage,
      ));
    }

    // 引用/回复
    items.add(MenuItemData(
      icon: Icon(
        Icons.format_quote,
        color: Colors.white,
        size: 20.w,
      ),
      title: StrRes.menuReply,
      onTap: () => onQuoteMessage?.call(message),
    ));

    // 删除
    items.add(MenuItemData(
      icon: Icon(
        Icons.delete_outline,
        color: Colors.white,
        size: 20.w,
      ),
      title: StrRes.menuDel,
      onTap: () => onDeleteMessage?.call(message),
    ));

    // 撤回 - 仅自己发送的消息且在时间限制内
    if (isISend && _canRevoke()) {
      items.add(MenuItemData(
        icon: Icon(
          Icons.undo,
          color: Colors.white,
          size: 20.w,
        ),
        title: StrRes.menuRevoke,
        onTap: () => onRevokeMessage?.call(message),
      ));
    }

    // 转发
    items.add(MenuItemData(
      icon: Icon(
        Icons.forward,
        color: Colors.white,
        size: 20.w,
      ),
      title: StrRes.menuForward,
      onTap: () => onForwardMessage?.call(message),
    ));

    // 多选
    items.add(MenuItemData(
      icon: Icon(
        Icons.checklist,
        color: Colors.white,
        size: 20.w,
      ),
      title: StrRes.menuMulti,
      onTap: () => onMultiSelectMessage?.call(message),
    ));

    // 置顶/取消置顶 - 仅在群聊中显示且有权限时显示
    if (!isSingleChat && canPinMessage) {
      final isPinned = _isMessagePinned();
      items.add(MenuItemData(
        icon: Icon(
          isPinned ? Icons.push_pin : Icons.push_pin_outlined,
          color: Colors.white,
          size: 20.w,
        ),
        title: isPinned ? '取消置顶' : '置顶',
        onTap: () => onPinMessage?.call(message),
      ));
    }

    return items;
  }

  bool _isMessagePinned() {
    return isMessagePinned;
  }
  
  void _copyMessage() {
    if (message.isTextType && message.textElem?.content != null) {
      Clipboard.setData(ClipboardData(text: message.textElem!.content!));
      IMViews.showToast(StrRes.copySuccessfully);
      onCopyMessage?.call(message);
    }
  }

  bool _canRevoke() {
    // 检查消息是否可以撤回（通常有时间限制，比如2分钟内）
    final now = DateTime.now().millisecondsSinceEpoch;
    final sendTime = message.sendTime ?? 0;
    final timeDiff = now - sendTime;
    const revokeTimeLimit = 2 * 60 * 1000; // 2分钟
    
    return timeDiff <= revokeTimeLimit;
  }
}

class MenuItemData {
  final Widget icon;
  final String title;
  final VoidCallback? onTap;

  MenuItemData({
    required this.icon,
    required this.title,
    this.onTap,
  });
}